package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.RepairQuestions;
import com.pj.wisdomlogistics.mvp.contract.RepairContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.RepairPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.adapter.GridImageAdapter;
import com.pj.wisdomlogistics.ui.view.GridSpacingItemDecoration;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.DensityUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RepairActivity extends MvpActivity<RepairPresenter> implements RepairContract.View, OnDateSetListener, BaseActivity.RequestPermission {
    @BindView(R.id.flowlayout)
    TagFlowLayout mFlowLayout;
    @BindView(R.id.iv_starttime)
    ImageView mIvStarttime;
    @BindView(R.id.tv_starttime)
    TextView mTvStarttime;
    @BindView(R.id.iv_endtime)
    ImageView mIvEndtime;
    @BindView(R.id.tv_endtime)
    TextView mTvEndtime;
    @BindView(R.id.rv_select_pic)
    RecyclerView mRvSelectPic;
    @BindView(R.id.et_fault_location)
    EditText mEtFaultLocation;
    @BindView(R.id.et_fault_phenomenon)
    EditText mEtFaultPhenomenon;
    @BindView(R.id.et_fault_remarks)
    EditText mEtFaultRemarks;
    @BindView(R.id.ll_yuyue)
    LinearLayout mLlYuyue;
    @BindView(R.id.tv_yuyue)
    TextView mTvYuyue;
    @BindView(R.id.rb_place_zf)
    RadioButton mRbPlaceZf;
    @BindView(R.id.rb_place_shy)
    RadioButton mRbPlaceShy;


    private boolean isSelectStartTime;
    long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
    private GridImageAdapter mAdapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 3;

    private List<RepairQuestions> mQuestionsList;
    private boolean isYuyue = false;

    @Override
    public void onError(int errorCode, String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this ,errorMsg , 1000);
    }

    @Override
    public void onSuccess(double id) {
        dismissProgressDialog();
        Intent mIntent = new Intent(this, SuccessActivity.class);
        mIntent.putExtra(Cons.RepairInfo.REPAIR_ID, (int)id);
        startActivity(mIntent);
        ActivityManagerUtil.create().finishActivity();
    }

    @Override
    public void onFindSuccess(final List<RepairQuestions> mList) {
        mQuestionsList = mList;

        mFlowLayout.setAdapter(new TagAdapter<RepairQuestions>(mList) {
            @Override
            public View getView(FlowLayout parent, int position, RepairQuestions mTestQuestion) {
                LinearLayout mLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_flow_tv, mFlowLayout, false);
                TextView mTv = (TextView) mLayout.findViewById(R.id.tv_content);
                mTv.setText(mTestQuestion.getQuestionName());
                return mLayout;
            }
        });

        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                ImageView mIv = (ImageView) view.findViewById(R.id.iv_select);
                LinearLayout mLayout = (LinearLayout) view.findViewById(R.id.layout);
                if (mList.get(position).isSelect()) {
                    mLayout.setBackgroundResource(R.drawable.flow_unselect);
                    mIv.setVisibility(View.GONE);
                    mList.get(position).setSelect(false);
                } else {
                    mLayout.setBackgroundResource(R.drawable.flow_select);
                    mIv.setVisibility(View.VISIBLE);
                    mList.get(position).setSelect(true);
                }
                return true;
            }
        });

    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        mPresenter.findQuestions();

        setRequestPermissionListener(this);

        if (!checkPermission(Manifest.permission.CAMERA)) {
            requestSystemPermissions(new String[]{Manifest.permission.CAMERA}, 111);
        }

        mRvSelectPic.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        mRvSelectPic.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(2), false));
        mAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mAdapter.setList(selectList);
        mAdapter.setSelectMax(maxSelectNum);
        mRvSelectPic.setAdapter(mAdapter);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_repair;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }


    @OnClick({R.id.iv_back, R.id.tv_send, R.id.tv_starttime, R.id.tv_endtime, R.id.tv_yuyue})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.tv_send:
                if (mFlowLayout.getSelectedList().size() == 0) {
                    CustomToast.showToast(this ,"请选择报修事项" , 1000);
                    return;
                }
                String questions = "";
                for (int position : mFlowLayout.getSelectedList()) {
                    questions += mQuestionsList.get(position).getQuestionID() + ",";
                }
                questions = questions.substring(0, questions.length() - 1);

                final String questionStr = questions;

                final String yStartTime = mTvStarttime.getText().toString().trim();
                final String yEndTime = mTvEndtime.getText().toString().trim();
                if (!TextUtils.isEmpty(yStartTime) && !TextUtils.isEmpty(yEndTime)) {
                    SimpleDateFormat mSimpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try {
                        Date startDate = mSimpleDateFormat1.parse(yStartTime);
                        Date endDate = mSimpleDateFormat1.parse(yEndTime);
                        if (startDate.after(endDate)) {
                            CustomToast.showToast(this ,"预约时间选择有误" , 1000);
                            return;
                        }
                    } catch (ParseException mE) {
                        mE.printStackTrace();
                    }
                } else if ((TextUtils.isEmpty(yStartTime) && !TextUtils.isEmpty(yEndTime))
                        || (TextUtils.isEmpty(yEndTime) && !TextUtils.isEmpty(yStartTime))) {
                    CustomToast.showToast(this ,"请将时间填写完整" , 1000);
                    return;
                }




                final String faultLocation = mEtFaultLocation.getText().toString().trim();
                final String faultPhenomenon = mEtFaultPhenomenon.getText().toString().trim();
                final String faultRemarks = mEtFaultRemarks.getText().toString().trim();
                final String place = mRbPlaceZf.isChecked() ? "1" : "2";

                if (TextUtils.isEmpty(faultLocation) || TextUtils.isEmpty(faultPhenomenon)) {
                    CustomToast.showToast(this ,"请将信息填写完整" , 1000);
                    return;
                }


                if (selectList.size() == 0) {
                    mPresenter.submitRepairApply(
                            MyApplication.userID,
                            questionStr,
                            yStartTime,
                            yEndTime,
                            faultLocation,
                            faultPhenomenon,
                            faultRemarks,
                            null,
                            place
                    );
                    return;
                }

                List<String> imagePath = new ArrayList<>(selectList.size());
                for (LocalMedia localMedia : selectList) {
                    imagePath.add(localMedia.getPath());
                }

                Luban.get(this)
                        .loadFiles(imagePath)
                        .putGear(Luban.THIRD_GEAR)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {

                            }

                            @Override
                            public void onSuccess(List<File> files) {
                                mPresenter.submitRepairApply(
                                        MyApplication.userID,
                                        questionStr,
                                        yStartTime,
                                        yEndTime,
                                        faultLocation,
                                        faultPhenomenon,
                                        faultRemarks,
                                        files,
                                        place
                                );
                            }

                            @Override
                            public void onError(Throwable e) {
                                CustomToast.showToast(RepairActivity.this ,"图片压缩失败，请重新尝试" , 1000);
                            }
                        })
                        .compress();

                showProgressDialog();


                break;
            case R.id.tv_starttime:
                isSelectStartTime = true;
                mIvStarttime.setImageResource(R.drawable.time_select);
                mTvStarttime.setBackgroundResource(R.drawable.repair_select_time);
                mIvEndtime.setImageResource(R.drawable.time);
                mTvEndtime.setBackgroundResource(R.drawable.repair_unselect_time);
                mTvStarttime.setTextColor(getResources().getColor(R.color.text_blue));
                mTvEndtime.setTextColor(getResources().getColor(R.color.text_normal));
                showTime(System.currentTimeMillis());
                break;
            case R.id.tv_endtime:
                if (TextUtils.isEmpty(mTvStarttime.getText().toString())) {
                    CustomToast.showToast(RepairActivity.this ,"请选择起始预约时间" , 1000);
                    return;
                }
                isSelectStartTime = false;
                mIvStarttime.setImageResource(R.drawable.time);
                mTvStarttime.setBackgroundResource(R.drawable.repair_unselect_time);
                mIvEndtime.setImageResource(R.drawable.time_select);
                mTvEndtime.setBackgroundResource(R.drawable.repair_select_time);
                mTvStarttime.setTextColor(getResources().getColor(R.color.text_normal));
                mTvEndtime.setTextColor(getResources().getColor(R.color.text_blue));
                try {
                    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
                    Date startDate = mSimpleDateFormat.parse(mTvStarttime.getText().toString().trim());
                    showTime(startDate.getTime());
                } catch (ParseException mE) {
                    mE.printStackTrace();
                }
                break;
            case R.id.tv_yuyue:
                if (isYuyue) {
                    mLlYuyue.setVisibility(View.GONE);
                    mTvYuyue.setText("预约");
                    isYuyue = !isYuyue;
                } else {
                    mLlYuyue.setVisibility(View.VISIBLE);
                    mTvYuyue.setText("取消预约");
                    isYuyue = !isYuyue;
                }
                break;
        }

    }

    private void showTime(long startTime) {
        TimePickerDialog mDialogAll = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确认")
                .setTitleStringId("预约时间")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(startTime)
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(startTime)
                .setThemeColor(getResources().getColor(R.color.text_blue))
                .setType(Type.MONTH_DAY_HOUR_MIN)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.text_gray))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.text_normal))
                .setWheelItemTextSize(12)
                .build();
        mDialogAll.show(getSupportFragmentManager(), "all");
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (isSelectStartTime) {
            mTvStarttime.setText(new SimpleDateFormat("MM-dd HH:mm").format(new Date(millseconds)));
        } else {
            mTvEndtime.setText(new SimpleDateFormat("MM-dd HH:mm").format(new Date(millseconds)));
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(RepairActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    //.compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .compress(false)// 是否压缩
                    //.compressMode(LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    //.glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    mAdapter.setList(selectList);
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 111) {
            if (!checkPermission(Manifest.permission.CAMERA)) {
                CustomToast.showToast(RepairActivity.this ,"您拒绝了拍照权限，该功能无法使用！" , 1000);
                ActivityManagerUtil.create().finishActivity();
            }
        }
    }


}
